package com.ruoyi.web.controller.system;

import com.ruoyi.system.domain.MonitorRule;
import com.ruoyi.system.domain.Project;
import com.ruoyi.system.domain.ProjectScenarioRule;
import com.ruoyi.system.domain.ValidationGroups.Create;
import com.ruoyi.system.domain.ValidationGroups.Select;
import com.ruoyi.system.domain.ValidationGroups.Update;
import com.ruoyi.system.domain.vo.QueryVo;
import com.ruoyi.system.service.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;

import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.validation.constraints.NotNull;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;

@SuppressWarnings("AlibabaLowerCamelCaseVariableNaming")
@Slf4j
@RestController
@RequestMapping("/system/project.v2")
public class ProjectScenarioRuleController extends BaseController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    IProjectScenarioRuleService projectScenarioRuleService;

    @Autowired
    IProjectScenarioActionService projectScenarioActionService;

    @Autowired
    IMonitorRuleService monitorRuleService;

    @Autowired
    IProjectService projectService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ISysUserService sysUserService;

    private AjaxResult checkExistance(ProjectScenarioRule projectScenarioRule) {
        Map<String, Object> existance = projectScenarioRuleService.findExistance(projectScenarioRule);
        if (existance != null) {
            Object name_exists = existance.get("name_exists");
            if (name_exists != null && Integer.parseInt(name_exists.toString()) > 0) {
                return AjaxResult.error(HttpStatus.ERROR, "场景联动规则名称已经存在");
            }
        }
        return null;
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:rule:add')")
    @PostMapping(value = "/scenario/rule/add", produces = "application/json;charset=UTF-8")
    @Log(title = "场景联动规则", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody @Validated(Create.class) ProjectScenarioRule projectScenarioRule) {
        //TODO 验证当前用户是否授权该项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectScenarioRule.getProjectId());
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", projectScenarioRule.getProjectId());
        Project project = projectService.retrieve(queryVo);
        if (project == null) {
            return AjaxResult.error("没有找到指定的项目");
        }
        queryVo.filters.clear();
        queryVo.filters.put("id", projectScenarioRule.getMonitorRuleId());
        MonitorRule monitorRule = monitorRuleService.retrieve(queryVo);
        if (monitorRule == null) {
            return AjaxResult.error("没有找到指定的监控规则");
        }
        //LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        String createBy = loginUser.getUsername();
        projectScenarioRule.setCompanyId(companyId);
        projectScenarioRule.setCreateBy(createBy);
        projectScenarioRule.setCreateTime(new Date());
        AjaxResult ret = checkExistance(projectScenarioRule);
        if (ret != null) {
            return ret;
        }
        Integer id = projectScenarioRuleService.create(projectScenarioRule);
        if (id != null) {
            return AjaxResult.success(projectScenarioRule);
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:rule:list')")
    @GetMapping(value = "/scenario/rule/list", produces = "application/json;charset=UTF-8")
    public Object index(@Validated(Select.class) ProjectScenarioRule projectScenarioRule) {
        //TODO 验证当前用户是否授权该项目
        if (projectScenarioRule != null){
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
            if (!commonRoleFlag){
                projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectScenarioRule.getProjectId());
            }
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("name", projectScenarioRule.getName());
        queryVo.filters.put("project_id", projectScenarioRule.getProjectId());
        queryVo.filters.put("monitor_rule_id", projectScenarioRule.getMonitorRuleId());
        queryVo.filters.put("monitor_rule_name", projectScenarioRule.getMonitorRuleName());
        startPage();
        List<ProjectScenarioRule> projectScenarioRules = projectScenarioRuleService.index(queryVo);
        return getDataTable(projectScenarioRules);
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:rule:available')")
    @GetMapping(value = "/scenario/rule/available", produces = "application/json;charset=UTF-8")
    public AjaxResult availableMonitorRuleList(@RequestParam("projectId") @NotNull(message = "项目id不能为null") Integer projectId) {
        //TODO 验证当前用户是否授权该项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectId);
        }
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("project_id", projectId);
        List<Map<String, Object>> available = projectScenarioRuleService.available(queryVo);
        return AjaxResult.success(available);
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:rule:query')")
    @GetMapping(value = "/scenario/rule/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult retrieve(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        ProjectScenarioRule projectScenarioRule = projectScenarioRuleService.retrieve(queryVo);
        if (projectScenarioRule == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        //TODO 验证当前用户是否授权该项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectScenarioRule.getProjectId());
        }
        return AjaxResult.success(projectScenarioRule);
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:rule:edit')")
    @Log(title = "场景联动规则", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/scenario/rule/edit", produces = "application/json;charset=UTF-8")
    public AjaxResult edit(@RequestBody @Validated(Update.class) ProjectScenarioRule projectScenarioRule) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", projectScenarioRule.getId());
        ProjectScenarioRule target = projectScenarioRuleService.retrieve(queryVo);
        if (target == null) {
            return AjaxResult.error(HttpStatus.NOT_FOUND, MessageUtils.message("error.not_found"));
        }
        //TODO 验证当前用户是否授权该项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectScenarioRule.getProjectId());
        projectScenarioRule.setCompanyId(target.getCompanyId());
        AjaxResult ret = checkExistance(projectScenarioRule);
        if (ret != null) {
            return ret;
        }
        if (projectScenarioRuleService.update(projectScenarioRule)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }

    @PreAuthorize("@ss.hasPermi('system:project:scenario:rule:remove')")
    @Log(title = "场景联动规则", businessType = BusinessType.DELETE)
    @DeleteMapping(value = "/scenario/rule/{id}", produces = "application/json;charset=UTF-8")
    public AjaxResult remove(@PathVariable("id") @NotNull(message = "id不能为null") Integer id) {
        QueryVo queryVo = new QueryVo();
        queryVo.filters.put("id", id);
        ProjectScenarioRule projectScenarioRule = projectScenarioRuleService.retrieve(queryVo);
        if (projectScenarioRule != null){
            //TODO 验证当前用户是否授权该项目
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectScenarioRule.getProjectId());
        }
        if (projectScenarioRuleService.delete(queryVo)) {
            return AjaxResult.success();
        }
        return AjaxResult.error(MessageUtils.message("error.operation_failed"));
    }
}
